
/*图片上传 预览 压缩*/

/**
 * 
 * @param {*} file 图片文件 必填
 * @param {*} obj  {quality:0.2,width:100,height:200} 压缩参数 宽度 高度
 * @param {*} size 限制size图片大小，最小1M
 * @param {*} callback 回调函数 必填
 */
function photoData(file, obj, size, callback) {
    var ready = new FileReader();
    ready.readAsDataURL(file);
    ready.onload = function () {
        // 取整，所以小于1M不会压缩
        if (size && (parseInt(file.size / 1024000) > size)) {
            //压缩
            canvasCompress(this.result, obj, callback);
        } else {
            //不压缩 img.src=this.result实现预览
            callback(this.result);
        }
    }
}

/**
 * canvas压缩
 * @param {*} result 图片文件
 * @param {*} obj    参数
 * @param {*} callback 回调
 */
function canvasCompress(result, obj, callback) {
    var img = new Image();
    img.src = result;
    img.onload = function () {
        var that = this;
        // 默认按比例压缩
        var w = that.width,
            h = that.height,
            scale = w / h;

        w = obj.width || w;
        h = obj.height || (w / scale);

        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var canvasw = document.createAttribute("width");
        canvasw.nodeValue = w;
        var canvash = document.createAttribute("height");
        canvash.nodeValue = h;
        canvas.setAttributeNode(canvasw);
        canvas.setAttributeNode(canvash);
        ctx.drawImage(that, 0, 0, w, h);
        // 图像质量
        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
            quality = obj.quality;
        }
        // quality值越小，所绘制出的图像越模糊
        var base64 = canvas.toDataURL('image/jpeg', quality);
        // 回调函数返回base64的值
        callback(base64);
    }
}

/**
 * base64的图片转换为Blob
 * @param {*} urlData base64的图片url数据
 */
function convertBase64UrlToBlob(urlData) {
    var arr = urlData.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
